﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Office.Interop.Excel;

namespace WFL.Office.Excel
{
    public class ExcelWorkbook : DisposableSite
    {
        private readonly object _lock = new object();

        private ExcelSheets _sheets;
        public ExcelSheets Sheets
        {
            get
            {
                if (_sheets == null)
                {
                    lock (_lock) { if (_sheets == null) { _sheets = new ExcelSheets(_workbook.Sheets) { Application = Application }; } }
                }
                return _sheets;
            }
        }

        private Workbook _workbook;

        private ExcelApplication _application;
        public ExcelApplication Application
        {
            get { return _application; }
            internal set { _application = value; }
        }

        internal ExcelWorkbook(Workbook workbook)
        {
            _workbook = workbook;
        }

        public void SaveAs(string path)
        {
            string extension = Path.GetExtension(path);
            if (extension == ".xls")
            {
                _workbook.SaveAs(path, XlFileFormat.xlWorkbookNormal);
            }
            else
            {
#if Excel2003
                _workbook.SaveAs(path, XlFileFormat.xlWorkbookNormal);
#else
                _workbook.SaveAs(path, XlFileFormat.xlWorkbookDefault);
#endif
            }
        }

        public void Close()
        {
            _workbook.Close();
        }

        protected override void Dispose(bool disposing)
        {
            if (_workbook != null)
            {
                if (disposing)
                {
                    ExcelSheets sheets = _sheets;
                    if (sheets != null)
                    {
                        _sheets = null;
                        sheets.Dispose();
                    }
                    Marshal.ReleaseComObject(_workbook);
                }
                _workbook = null;
                _application = null;
                base.Dispose(disposing);
            }
        }
    }
}
